<?php

if (!class_exists("stthemecontroller")) {

    class stthemecontroller {

        protected static $_instance = null;
        public $view = null;
        public $config = array();
        public $layout = "default";
        public $actionName = "index";
        public $isAjax = 0;
        public $tabMenu = array();
        public $views = array();
        public $option = "";

        public function __construct($config) {
            $this->setConfig($config);
            if (get_option('permalink_structure') != '') {
                $url = $_SERVER['REQUEST_URI'];

                $home_url = get_home_url('/');

                $parts = parse_url($home_url);
                /*                 * * return the host domain ** */
                $url = $parts['scheme'] . '://' . $parts['host'] . $url;

                $url = str_replace($home_url, '', $url);
                $url_tmp = explode('/', $url);
                foreach ($url_tmp as $value) {
                    if ($value != '') {
                        $title_tmp = $value;
                        break;
                    }
                }

                if ($title_tmp != '') {
                    $this->actionName = $title_tmp;
                }
            }
            if (isset($_REQUEST['action'])) {
                $this->actionName = $_REQUEST['action'];
            }
            $this->layout = $this->config ['default_layout'];
            $this->isAjax = false;
            $this->view = new stthemeview();
            $this->view->config = $this->config;
            $this->functions = new themeFunctions($this->config);
            $this->option = get_option($this->config['theme_name'] . '_' . $this->config['option_key'] . '_settings');
        }

        public function __destruct() {}

        public function addAdmin() {  
            $this->addScriptAndStyle();  
            if ($_REQUEST['ajax'] == 0) {
                $this->execute();
            } else {
                if (isset($_REQUEST['page'])) {
                    if($_REQUEST['page'] == $this->config['theme_name'])
                        $this->ajaxAction();
                } else {
                    $this->ajaxAction();
                }
            }
        }

        protected function ajaxAction() {
            $this->isAjax = true;
            $this->execute();
            die;
        }

        protected static function getInstance() {
            if (null === self::$_instance) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }

        protected function setConfig($config) {
            $this->config = $config;
            if ($this->actionName == "index") {
                $this->actionName = $config['default_action'];
            }

            $this->config['themeDir'] = TEMPLATEPATH . '/theme-functions/';
            $this->config['includePath'] = TEMPLATEPATH . '/stInclude/';
            $this->config['cssUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/theme-functions/css/';
            $this->config['scriptUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/theme-functions/scripts/';
            $this->config['imagesUrl'] = WP_CONTENT_URL . '/themes/' . $this->config['theme_name'] . '/theme-functions/images/';
        }
        
        public function addScriptAndStyle(){
            $method = array($this, 'loadDefaultStyle' );
            add_action( "wp_print_styles", $method );
            $method = array($this, 'loadDefaultScript' );
            add_action( "wp_print_scripts", $method );
            //Custom script ans style
            $method = array($this, 'loadCss' );
            add_action( "wp_print_styles", $method );
            $method = array($this, 'loadScript' );
            add_action( "wp_print_scripts", $method );
        }
        
        public function loadDefaultScript() {
            //this is function import javascript
            wp_enqueue_script('jQueryUI', $this->config ['scriptUrl'] . 'jquery-ui-1.8.7.custom.min.js', array('jquery'), '1.8.7');
//            wp_enqueue_script('validate', $this->config ['scriptUrl'] . 'jquery.validate.pack.js', array('jquery'), '1.5.5');
//            wp_enqueue_script('stCore', $this->config ['scriptUrl'] . 'sttheme.js', array('jquery'), '1.0');
//            wp_enqueue_script('ajaxupload', $this->config ['scriptUrl'] . 'ajaxupload.js', array('jquery'), '1.0');
//            wp_enqueue_script('blockUI', $this->config ['scriptUrl'] . 'jquery.blockUI.js', array('jquery'), '2.36');
//            wp_enqueue_script('prettyPhoto', $this->config ['scriptUrl'] . 'jquery.prettyPhoto.js', array('jquery'), '3.0');
        }

        public function loadDefaultStyle() {            
            wp_enqueue_style('jQueryUI', $this->config ['cssUrl'] . 'jquery-ui/jquery-ui-1.8.7.custom.css');
            wp_enqueue_style('prettyphoto', $this->config ['cssUrl'] . 'prettyphoto/prettyPhoto.css');
            wp_enqueue_style('stStyle', $this->config ['cssUrl'] . 'style.css');
            wp_enqueue_style('stCustomStyle', $this->config ['cssUrl'] . 'custom.css');
        }

        public function customEnqueueScript() {}

        public function loadCss() {}

        public function loadScript() {}

        public function execute() {

            if (is_callable(array($this, $this->actionName)) == false) {
                //die("<br />Action not found: <b>Class: ". $this->config['theme_name'] ."Controller, Action: ". $this->actionName ."</b> in " . __FILE__);
            } else {
                if (in_array($this->actionName, array_keys($this->views))) {

                    //Get view
                    $actionNameCall = $this->actionName;
                    $this->$actionNameCall();

                    $data = $this->view->getData();
                    $data ['current_action'] = $this->actionName;
                    $output = get_include_contents($this->config['themeDir'] . "/views/{$this->actionName}.php", $data);

                    if ($this->isAjax) {
                        echo $output;
                    } else {

                        $data = $this->view->getData();
                        $data['content'] = $output;
                        $data['config'] = $this->config;
                        $data['tabmenus'] = $this->tabMenu;
                        $data ['current_action'] = $this->actionName;
                        $data ['option'] = $this->option;
                        $this->layout = $this->views[$this->actionName];
                        if (empty($this->layout))
                            $this->layout = $this->config['default_layout'];
                        $layout = get_include_contents($this->config['themeDir'] . "/views/layout/{$this->layout}.php", $data);
                        echo $layout;
                        exit;
                    }
                }
            }
        }

        protected function index() {}

        protected function setView($views) {
            foreach ($views as $view => $layout) {
                $this->views[$view] = $layout;
            }
        }

        protected function registerView() {}

        public function getAction($action = '', $agrs = ''){
            if($action != '' && !is_object($action)){
                $actionNameCall = $action;
            }
            else{
                $actionNameCall = $this->actionName;
            }
            if($agrs != '' )
                $this->$actionNameCall ($agrs);
            else
                $this->$actionNameCall ();
            $data = $this->view->getData();
            $data ['current_action'] = $actionNameCall;
            $output = get_include_contents ( $this->config ['themeDir'] . "views/{$actionNameCall}.php", $data );

            if($action != '' && !is_object($action)){
                return $output;
            }else{
                echo $output;
            }

        }

        public function loadmodel($modelName) {
            $className = $modelName . "_model";
            $fileName = $this->config['includePath'] . "models/{$modelName}.php";
            require_once $fileName;
            $obj = new $className($this->config);
            return $obj;
        }

        protected function updateOption($data = '', $value = ''){
            $option = get_option($this->config['theme_name'].'_'.$this->config['option_key'].'_settings');
            if(is_array($data) >0 ){
                foreach ($data as $key => $value) {
                    $option[$key] = $value;
                }
            }else{
                $option[$data] = $value;
            }

            if(update_option($this->config['theme_name'].'_'.$this->config['option_key'].'_settings', $option)){
                return true;
            }else{
                return false;
            }
        }

        public function ajaxPostAction() {
            $save_type = $_POST['type'];
            //Uploads
            if ($save_type == 'upload') {
                $clickedID = $_POST['data']; // Acts as the name
                $filename = $_FILES[$clickedID];
                $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                $override['test_form'] = false;
                $override['action'] = 'wp_handle_upload';
                $uploaded_file = wp_handle_upload($filename, $override);
                list($width, $height) = getimagesize($uploaded_file['file']);
                if ($_POST['thumbnail_width'] != '') {
                    $max_w = $_POST['thumbnail_width'];
                    $max_h = round(($max_w * $height) / $width);
                    if (isset($uploaded_file['file'])) {
                        $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                        $thumbnail_url = $upload_dir_url . basename($thumbnail);
                    }
                }

                if (!empty($uploaded_file['error'])) {
                    echo 'Upload Error: ' . $uploaded_file['error'] . "|*| Upload Error";
                } else {
                    echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                } // Is the Response
            } elseif ($save_type == 'image_remove') {
                $file = $_POST['file']; // Acts as the name
                $img_name = basename($file);
                $img_name = explode('.', $img_name);
                $img_name = $img_name[0];
                $file_thumb = str_replace($img_name, $img_name . '-thumb', $file);
                unlink($file);
                unlink($file_thumb);
            }
        }

    }

}
?>